package com.wiscamp.ninechapters.problems.infrastructure.mappers.collections;

import com.wiscamp.ninechapters.problems.infrastructure.po.collections.ProblemCollectionPO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * 题集仓储对象
 *
 * @author yifeng
 */
@Repository
public interface ProblemCollectionMapper extends JpaRepository<ProblemCollectionPO, Long>, JpaSpecificationExecutor<ProblemCollectionPO> {
    /**
     * 通过题集编号更新题集所属题数量
     *
     * @param collectionId
     */
    @Transactional(transactionManager = "problemsTransactionManager")
    @Modifying
    @Query(nativeQuery = true, value = "update problem_collections e set e.problem_quantity = (select count(pi.problem_id) from collection_problems pi, problem i where i.problem_id = pi.problem_id and i.is_deleted = false and pi.collection_id = :collectionId) where e.collection_id = :collectionId")
    void updateProblemQuantity(long collectionId);
}